#!/usr/bin/bash
pro_base="$(cd `dirname $(readlink -f $0)`;pwd)"
pro_root="${pro_base##*/}"
source ${pro_base}/shared/include.sh || exit 1
Include ${pro_base}/shared/prompt.sh

Eval_cont "bash ${pro_base}/firewall.sh clean"
# 关闭防火墙
Eval_cont 'systemctl stop firewalld; systemctl disable firewalld; systemctl status firewalld'
Eval_cont 'systemctl stop iptables ; systemctl disable iptables ; systemctl status iptables'

Eval_cont "mkdir -p /var/log/${pro_root}"
echo '#分 时 日 月 周 程序...' >> /var/spool/cron/root
echo "11 9 * * * find /var/log/${pro_root} -type f -mtime +32 -delete" >> /var/spool/cron/root

# cat命令: '-'表示忽略行首的<tab>,不会忽略行首的<space>,也不忽略行中间的<space>或<tab>; 'EOF'带了引号表示不扩展INPUT中的$a等变量
cat <<-'EOF' > /etc/rc.d/rc.local
#!/bin/bash
[[ -d /var/log/boot ]] || mkdir -p /var/log/boot
(
fnEvalCont(){
    echo -e "[ \033[1;33mINFO\033[0m ] `date '+%FT%T'` Running: \033[36m$@\033[0m"
    eval "$@"
}
echo -e "\033[1;36m`date '+%FT%T'`: start to run /etc/rc.local\033[0m"
#fnEvalCont "echo 'nameserver 223.5.5.5' >> /etc/resolv.conf"
#fnEvalCont /usr/sbin/ntpdate ntp1.aliyun.com

# # # # # # # # # # # # # # # # # # # # #
#fnEvalCont "bash ${pro_base}/firewall.sh clean"
# 这中间可以执行任何其他代码或脚本
# 注意:通过rc.local在开机时启动的程序,关机时要先关闭这些程序,否则关机时可能会一直卡在"a stop job is running for /etc/rc.d/rc.local"
# 解决方法:sed -i 's/^TimeoutSec=.*/TimeoutSec=9/' /usr/lib/systemd/system/rc-local.service && systemctl daemon-reload
# # # # # # # # # # # # # # # # # # # # #

echo -e "\033[1;36m`date '+%FT%T'`: finish to run /etc/rc.local\033[0m\n"
) &>> /var/log/boot/`date +%F`.log  # less -iR /var/log/boot/`date +%F`.log
EOF
Eval_cont 'chmod a+x /etc/rc.d/rc.local && ln -sf /etc/rc.d/rc.local /etc/rc.local && cat /etc/rc.local'
Eval_cont dnf -y install iftop ntpsec  # Fedora33没有ntpsec，仍有ntpdate

sed -i 's/^TimeoutSec=.*/TimeoutSec=9/' /usr/lib/systemd/system/rc-local.service && systemctl daemon-reload
Eval_cont 'grep TimeoutSec /usr/lib/systemd/system/rc-local.service'
sed -i '/^DefaultTimeout/d' /etc/systemd/system.conf && echo -e 'DefaultTimeoutStartSec=9s\nDefaultTimeoutStopSec=9s' >> /etc/systemd/system.conf
Eval_cont 'grep DefaultTimeout /etc/systemd/system.conf'

# 优化内核参数
Eval_cont bash ${pro_base}/initial_module/kernel.sh

sed -i '/^\*.*soft.*core/d; /^\*.*hard.*core/d' /etc/security/limits.conf
sed -i '/^\*.*soft.*nofile/d; /^\*.*hard.*nofile/d' /etc/security/limits.conf
echo -e '* soft nofile 65535\n* hard nofile 65535' >> /etc/security/limits.conf
Eval_cont "tail /etc/security/limits.conf"

# 使用适合自己的 bash 配置
sed -i '/^myVar=/d' /etc/environment; echo 'myVar="${myVar}:/etc/environment"' >> /etc/environment
echo -e 'myVar="${myVar}:/etc/profile.d/root.sh\nEDITOR=/usr/bin/vim"' > /etc/profile.d/root.sh
sed -i '/^myVar=/d' /etc/profile; echo 'myVar="${myVar}:/etc/profile"' >> /etc/profile
sed -i '/^myVar=/d' /etc/bashrc; echo 'myVar="${myVar}:/etc/bashrc"' >> /etc/bashrc
sed -i '/^myVar=/d' ${HOME}/.bashrc; echo 'myVar="${myVar}:${HOME}/.bashrc"' >> ${HOME}/.bashrc
sed -i '/^myVar=/d' ${HOME}/.bash_profile; echo 'myVar="${myVar}:${HOME}/.bash_profile"' >> ${HOME}/.bash_profile
sed -i '/^set editing-mode vi/d' /etc/inputrc; echo 'set editing-mode vi' >>/etc/inputrc
sed -i -r '/^PROMPT_COMMAND|^PS1=|^yumDir=|^scrDir=|HISTTIMEFORMAT|HISTCONTROL/d' /etc/bashrc                 # scrDir: directory of my script
PS="PS1='\[\033[32m\][\u\[\033[33m\]@\[\033[32m\]\h \[\033[33m\]\w]# \[\033[0m\]'"
echo "${PS}
yumDir='/etc/yum.repos.d'
scrDir='/usr/src/${pro_root}'
HISTTIMEFORMAT=\"%FT%T \"                           # HISTTIMEFORMAT变量仅用于设置history的时间格式
HISTSIZE=999
#HISTFILE=\"/tmp/\`whoami\`.history\"               # /tmp in fedora35 is a memory disk
#PROMPT_COMMAND=\"history -a && ${PROMPT_COMMAND}\" # 实时写入历史命令到\$HISTFILE
unset HISTCONTROL HISTFILESIZE" >>/etc/bashrc
Eval_cont 'tail /etc/bashrc'

# 修改dnf.conf
Eval_cont bash ${pro_base}/initial_module/dnf.conf.setting.sh

Eval_cont dnf install vnstat logrotate -y
Eval_cont 'systemctl enable vnstat && systemctl restart vnstat'
# 关闭SELinux
sed -i "s/^SELINUX=.*$/SELINUX=disable/" /etc/selinux/config && Eval_cont 'grep SELINUX /etc/selinux/config; setenforce 0; getenforce'
# 配置logrotate.conf
[[ $(grep -c 'dateyesterday' /etc/logrotate.conf) == 0 ]] && sed -i '/^dateext/a dateyesterday' /etc/logrotate.conf
Eval_cont 'grep --color=auto date /etc/logrotate.conf'

# 安装常用软件
Eval_cont 'dnf install -y net-tools psmisc lsof telnet bind-utils sysstat fontconfig mailx expect at'
                        # netstat, pstree,lsof,telnet,nslookup,  sar, 字体配置工具, mail,expect,at
Eval_cont 'dnf install -y wget mlocate bash-completion rsync pcp-system-tools' # pcp-system-tools include dstat
# 安装send_mail.pl的依赖组件
#Eval_cont "dnf install -y perl-MIME-Lite perl-Net-SMTP-SSL perl-Net-SSLeay perl-Authen-SASL openssl-perl openssl-devel perl-IO-Socket-SSL" || PWarn "send_mail.pl的一些依赖组件安装失败"
#Eval_exit "chmod +x ${pro_base}/shared/send_mail.pl && ln -sf ${pro_base}/shared/send_mail.pl /usr/bin"

# set vim
Eval_cont bash ${pro_base}/initial_module/vim_deploy.sh

Eval_cont "systemctl restart sshd && systemctl enable sshd"

PNote "需要生成 2GB 的 swap 空间吗？"
a="n"
read -p "是/否 (y/n 默认:n)" a
if [[ "$a" == "y" ]]; then
    # create 2GB swap       # btrfs doesn't need swap
    dd if=/dev/zero of=/swapfile bs=256M count=$((2*4)) && chmod 0600 /swapfile && mkswap /swapfile
    echo '/swapfile swap swap defaults 0 0' >> /etc/fstab && cat /etc/fstab
    Eval_cont "swapon /swapfile && free -h && cat /proc/swaps"
# 取消swap分区: swapoff /swapfile; sed -i '/swapfile/d' /etc/fstab; rm -rf /swapfile
fi

if [[ `systemctl get-default` == "graphical.target" ]]; then
	# 修改语言,需重启
	Eval_cont '(($(localectl |grep -c "en_US.UTF-8"))) || localectl set-locale LANG=en_US.UTF-8 && localectl'
	timedatectl set-timezone "Asia/Shanghai"
	timedatectl set-local-rtc 0
	Eval_cont 'dnf install -y featherpad xfce4-terminal'
	su administrator -c 'mkdir -p ~/.config/pcmanfm-qt/lxqt && touch ~/.config/pcmanfm-qt/lxqt/settings.conf'
echo '[Behavior]
AutoSelectionDelay=600
BookmarkOpenMethod=current_tab
ConfirmDelete=true
ConfirmTrash=false
CtrlRightClick=false
NoUsbTrash=false
QuickExec=false
SelectNewFiles=false
SingleClick=false
SingleWindowMode=false
UseTrash=true

[Desktop]
BgColor=#000000
DesktopCellMargins=@Size(3 1)
DesktopIconSize=48
DesktopShortcuts=@Invalid()
FgColor=#ffffff
Font="Sans,11,-1,5,50,0,0,0,0,0"
HideItems=false
LastSlide=
OpenWithDefaultFileManager=false
PerScreenWallpaper=false
ShadowColor=#000000
ShowHidden=true
ShowWmMenu=true
SlideShowInterval=0
SortColumn=name
SortFolderFirst=true
SortHiddenLast=false
SortOrder=ascending
TransformWallpaper=false
Wallpaper=/home/administrator/\x7d2b\x7f57\x5170.jpeg
WallpaperDialogSize=@Size(700 500)
WallpaperDialogSplitterPos=200
WallpaperDirectory=
WallpaperMode=center
WallpaperRandomize=false

[FolderView]
BackupAsHidden=false
BigIconSize=48
CustomColumnWidths=@Invalid()
FolderViewCellMargins=@Size(3 3)
HiddenColumns=@Invalid()
Mode=compact
NoItemTooltip=false
ShadowHidden=false
ShowFilter=true
ShowFullNames=false
ShowHidden=true
SidePaneIconSize=24
SmallIconSize=24
SortCaseSensitive=false
SortColumn=name
SortFolderFirst=true
SortHiddenLast=false
SortOrder=ascending
ThumbnailIconSize=128

[Places]
HiddenPlaces=@Invalid()
PlacesApplications=true
PlacesComputer=true
PlacesDesktop=true
PlacesHome=true
PlacesNetwork=true
PlacesRoot=true
PlacesTrash=true

[Search]
searchContentCaseInsensitive=false
searchContentRegexp=true
searchNameCaseInsensitive=false
searchNameRegexp=true
searchRecursive=false
searchhHidden=true

[System]
Archiver=file-roller
FallbackIconThemeName=oxygen
OnlyUserTemplates=false
SIUnit=false
SuCommand=lxqt-sudo %s
TemplateRunApp=false
TemplateTypeOnce=false
Terminal=xfce4-terminal

[Thumbnail]
MaxExternalThumbnailFileSize=-1
MaxThumbnailFileSize=4096
ShowThumbnails=true
ThumbnailLocalFilesOnly=true

[Volume]
AutoRun=true
CloseOnUnmount=true
MountOnStartup=true
MountRemovable=true

[Window]
AlwaysShowTabs=true
FixedHeight=480
FixedWidth=640
LastWindowHeight=480
LastWindowMaximized=true
LastWindowWidth=640
PathBarButtons=false
RememberWindowSize=true
ReopenLastTabs=false
ShowMenuBar=true
ShowTabClose=true
SidePaneMode=places
SidePaneVisible=true
SplitView=false
SplitterPos=150
SwitchToNewTab=false
TabPaths=@Invalid()' > /home/administrator/.config/pcmanfm-qt/lxqt/settings.conf
	Eval_cont 'grep Terminal /home/administrator/.config/pcmanfm-qt/lxqt/settings.conf'
fi
